﻿Imports System
Imports System.Data
Imports System.IO
Imports System.Text
Imports System.Diagnostics
Imports TextLineConfigurationFile
Imports HL7Objects

Public Class frmHL7Import

    Private mFileName As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CAREWareLabToolSettings.txt")
    'Private mFileName As String = ClsSQLhelper.HL7InboxPath

    Dim StrMssql As String
    Dim Mssql1 As New ClsSQLhelper
    Dim iQMysql As New ClsSQLhelper

    Private mLines As New Hashtable
    Private mDirectoryWatchName As String
    Private watcher As New IO.FileSystemWatcher
    Private tt As New myTTranslite_TypeLib.TTransliteCtrl

    Dim PathFileName As String = InboxOutboxController.Instance.InboxFolder
    'Dim DistinationPath As String = "C:\HL7InboxDest\"
    'Dim HL7OutboxPath As String = "C:\HL7Outbox\"
    Dim DistinationPath As String = ClsSQLhelper.HL7DestPath & Now().Year.ToString & "\" & Format(Now, "yyyyMM") & "\" & HL7Date() & "\"
    Dim HL7OutboxPath As String = ClsSQLhelper.HL7OutboxPath
    'Dim FILE_NAME As String = ClsSQLhelper.ExportPath + Me.txtOrder.Text + ".txt"

    
    'Dim Thai2RomanPath As String = "C:\Program Files\ThaiRoman"
    Dim Thai2RomanPath As String = ClsSQLhelper.Thai2RomanPath
    'Dim WadoServ As String = "http://192.168.1.5/"
    Dim WadoServ As String = ClsSQLhelper.WadoServ

    'Dim WadoUsername As String = "d3bcf609b91f4a348361a2ba7216912af57c487e398797fd544630cca6139031"
    Dim WadoUsername As String = ClsSQLhelper.WadoUsername
    'Dim WadoPassword As String = "fdf45c9cede41918e92fcaf9c13a43801b163c84be42e6698c6444b51ce85fba"
    Dim WadoPassword As String = ClsSQLhelper.WadoPassword
    'Dim WadoTTL As String = "ef324e0d51087715bed59441812e93bf99833c8e58faab7484af31ea811913fd"
    Dim WadoTTL As String = ClsSQLhelper.WadoTTL

    Dim FlagSegment As Integer = 0

    Const ver As String = "iQPACs Broker Ver.1.56.7.28"


    Private Sub cmdHL7toText_Click(sender As System.Object, e As System.EventArgs) Handles cmdHL7toText.Click
        ''===============Begin 7 Function HL7 ==================

        ' RichTextData.Text = HL7Objects.HL7.ToSegmentType(RichTextHL7.Text)    ' หาบรรทัด เช่น MSH = 0,PID =1

        ' RichTextData.Text = HL7Objects.HL7.ToSegmentTypeString(0)     ' ' หา Secment เช่น 0= MSH , 1 =PID 

        ' RichTextData.Text = HL7Objects.HL7.DateFromHL7String(20111206174303)   ' แปลง 20111206174303  ไปเป็น วันที่  6/12/2554 17:43:03

        ' RichTextData.Text = HL7Objects.HL7.DateToHL7String("6/12/2011 17:43:00")  '  แปลง 2011-12-06 17:43:03 ไปเป็น 20111206174303

        'Dim dataSS As String = "D:/sample.txt"
        'HL7Objects.HL7.FileToHL7Document(dataSS)            ' แปลง file to hl7 

        'HL7Objects.HL7.FileToHL7Document(dataSS)


        'Dim data1 As String = "D:/sample.txt"                '  แปลง HL7 to file 
        'Dim data2 As String = "D:/sample11.txt"
        'HL7Objects.HL7.HL7DocumentToFile(HL7Objects.HL7.FileToHL7Document(data1), data2)

        'Dim data3 As String = "D:/sample.txt"
        'HL7Objects.HL7.Delims("MSH ^~\& KHSOFT XRAY PACS PACS 20111206174303  ORM^O01 111880813 P 2.3 AL NE TH")   ' Check Header "MSH" ว่ามีข้อมูล OK หรือ ไม่


        ''===============END 7 Function HL7 ==================

    End Sub

    Private Sub frmHL7Import_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed

        ClearForm()

        If txtInterval.Text <> "" Then
            ClsSQLhelper.SecInterval = txtInterval.Text
        Else
            ClsSQLhelper.SecInterval = "4"
        End If


        If (chkEx2GDT.Checked) Then

            ClsSQLhelper.chkEx2GDT = "Y"
        Else
            ClsSQLhelper.chkEx2GDT = "N"
        End If


        If (chkiQTH2EN.Checked) Then

            ClsSQLhelper.chkiQTH2EN = "Y"
        Else
            ClsSQLhelper.chkiQTH2EN = "N"

        End If

        If chkConfirm.Checked Then
            ClsSQLhelper.chkConfirm = "Y"
        Else
            ClsSQLhelper.chkConfirm = "N"
        End If

        If (chkDiagReport.Checked) Then
            ClsSQLhelper.chkDiagReport = "Y"
        Else
            ClsSQLhelper.chkDiagReport = "N"
        End If

        frmMain.Show()
        Me.Hide()


    End Sub

    Private Sub frmHL7Import_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        Me.Text = ver

        inittialForm()

        ClearForm()

        Me.MdiParent = frmMain

        'DataGridViewX1.ColumnCount = 19
        'DataGridViewX1.Columns(0).HeaderText = "Product ID"
        'DataGridViewX1.Columns(1).HeaderText = "Product Name"
        'DataGridViewX1.Columns(2).HeaderText = "Product_Price"

    End Sub
    Private Sub inittialForm()

        If ClsSQLhelper.SecInterval <> "" Then
            txtInterval.Text = ClsSQLhelper.SecInterval
        Else

            txtInterval.Text = "3"

        End If

        If (ClsSQLhelper.chkEx2GDT) = "Y" Then
            chkEx2GDT.Checked = True
        Else
            chkEx2GDT.Checked = False
        End If


        If (ClsSQLhelper.chkiQTH2EN) = "Y" Then
            chkiQTH2EN.Checked = True
        Else
            chkiQTH2EN.Checked = False
        End If

        If (ClsSQLhelper.chkConfirm) = "Y" Then
            chkConfirm.Checked = True
        Else
            chkConfirm.Checked = False
        End If

        If (ClsSQLhelper.chkDiagReport) = "Y" Then
            chkDiagReport.Checked = True
        Else
            chkDiagReport.Checked = False
        End If



    End Sub

    Private Sub ClearForm()

        Me.txtConsole.Text = ""
        Me.txtAge.Text = ""
        Me.txtDoctorOrder.Text = ""
        Me.txtHN.Text = ""
        Me.txtModality.Text = ""
        Me.txtName.Text = ""
        Me.txtOrder.Text = ""
        Me.txtOrderDateTime.Text = ""
        Me.txtOrderDep.Text = ""
        Me.txtOrdertype.Text = ""
        Me.txtOrderTypeName.Text = ""
        Me.txtSex.Text = ""
        Me.txtBirthdate.Text = ""

    End Sub
    Private Sub listFile(filePath As String)
        Dim DS2 As New DataSet
        Dim strSQL As String
        If filePath Is Nothing Then
            Exit Sub
        Else

            Dim strFileSize As String = ""
            Dim di As New IO.DirectoryInfo(filePath)
            Dim aryFi As IO.FileInfo() = di.GetFiles("*.txt")
            Dim fi As IO.FileInfo

            For Each fi In aryFi

                Dim Datafile_Name As String = fi.Name


                strFileSize = (Math.Round(fi.Length / 1024)).ToString()

                'Me.txtConsole.Text = "File Name: " & fi.Name & vbNewLine & Me.txtConsole.Text
                'Me.txtConsole.Text = "Path Name: " & fi.FullName & vbNewLine & Me.txtConsole.Text
                'Me.txtConsole.Text = "File Size: " & strFileSize & vbNewLine & Me.txtConsole.Text
                'Me.txtConsole.Text = "File Extension: " & fi.Extension & vbNewLine & Me.txtConsole.Text
                'Me.txtConsole.Text = "File AccessTime: " & fi.LastAccessTime & vbNewLine & Me.txtConsole.Text

                '-------อ่าน File---------------
                ReadFile(fi.FullName)


                '--------Check Data Type NW CA or OX--------------
                Select Case Me.txtData_Type.Text

                    Case "NW"
                        '--------Check Duplicate----------
                        strSQL = "select ACCESSIONNUMBER from worklist_data where ACCESSIONNUMBER ='" & Me.txtOrder.Text & "' "

                        DS2 = Mssql1.GetMSSQLDataset(strSQL, "DS_worklist_data", "worklist_data")

                        If DS2.Tables(0).Rows.Count <= 0 Then

                            '--------Save Data to DB --------------]
                            If chkSaveData2DB.Checked Then

                                SaveDataToDB()

                            End If

                            '---Move File-------------------
                            MoveFiles(filePath, DistinationPath, Datafile_Name)

                            '---------------------

                            Me.txtConsole.Text = "NEW Order No.: " & txtOrder.Text & " [" & txtModality.Text & "] " & txtName.Text & " Order Name : " & txtOrderTypeName.Text & vbNewLine & Me.txtConsole.Text
                        Else
                            '---Move Duplicate File-------------------
                            MoveDupliCateFiles(filePath, DistinationPath, Datafile_Name)

                            Me.txtConsole.Text = "Duplicate NW Order No.: " & txtOrder.Text & " [" & txtModality.Text & "] " & txtName.Text & " Order Name : " & txtOrderTypeName.Text & vbNewLine & Me.txtConsole.Text


                        End If

                        '-------------

                    Case "CA"

                        '--------Check Duplicate----------
                        strSQL = "select ACCESSIONNUMBER from worklist_data where ACCESSIONNUMBER ='" & Me.txtOrder.Text & "' "

                        DS2 = Mssql1.GetMSSQLDataset(strSQL, "DS_worklist_data", "worklist_data")

                        If DS2.Tables(0).Rows.Count > 0 Then

                            '--------Save Data to DB --------------]
                            'If chkSaveData2DB.Checked Then

                            DelDataDB(Me.txtOrder.Text)

                            'End If

                            '---Move File-------------------
                            MoveFiles(filePath, DistinationPath, Datafile_Name)

                            '---------------------

                            Me.txtConsole.Text = "Delete Order No.: " & txtOrder.Text & " [" & txtModality.Text & "] " & txtName.Text & " Order Name : " & txtOrderTypeName.Text & vbNewLine & Me.txtConsole.Text
                        Else

                            '---Move File-------------------


                            'MoveFiles(filePath, DistinationPath, Datafile_Name)
                            MoveDupliCateFiles(filePath, DistinationPath, Datafile_Name)

                            '---------------------

                            Me.txtConsole.Text = "Duplicate Delete Order No.: " & txtOrder.Text & " [" & txtModality.Text & "] " & txtName.Text & " Order Name : " & txtOrderTypeName.Text & vbNewLine & Me.txtConsole.Text

                        End If

        '-------------

                       
                    Case "XO"
                        '--------Check Duplicate----------
                        strSQL = "select ACCESSIONNUMBER from worklist_data where ACCESSIONNUMBER ='" & Me.txtOrder.Text & "' "

                        DS2 = Mssql1.GetMSSQLDataset(strSQL, "DS_worklist_data", "worklist_data")

                        If DS2.Tables(0).Rows.Count <= 0 Then

                            '--------Save Data to DB --------------]
                            If chkSaveData2DB.Checked Then

                                'ReCreateDataToDB()
                                SaveDataToDB()

                            End If

                            '---Move File-------------------
                            MoveFiles(filePath, DistinationPath, Datafile_Name)

                            '---------------------

                            Me.txtConsole.Text = "ReCreate Order No.: " & txtOrder.Text & " [" & txtModality.Text & "] " & txtName.Text & " Order Name : " & txtOrderTypeName.Text & vbNewLine & Me.txtConsole.Text
                        Else

                            '------Move Duplicate File----------------
                            MoveDupliCateFiles(filePath, DistinationPath, Datafile_Name)

                            Me.txtConsole.Text = "Duplicate Re Order No.: " & txtOrder.Text & " [" & txtModality.Text & "] " & txtName.Text & " Order Name : " & txtOrderTypeName.Text & vbNewLine & Me.txtConsole.Text


                        End If


                End Select

                '-------------------------------------------------


                

            Next

            '----------------------
            'MoveFiles(filePath, DistinationPath)

            '---------------------

        End If
    End Sub
    Private Function DelDataDB(OrderNo_data As String)
        Dim StrMssql1 As String
        Dim StrMssql2 As String
        Dim iQstrSql1 As String
        Dim iQstrSql2 As String
        Dim DS3 As New DataSet
        Dim iQDS1 As New DataSet

        ' Delete MsSQL-----
        StrMssql1 = "select ACCESSIONNUMBER from worklist_data where ACCESSIONNUMBER ='" & Me.txtOrder.Text & "' AND (ST_EXPORT <>'1' OR ST_REPORT <> '1' ) "

        DS3 = Mssql1.GetMSSQLDataset(StrMssql1, "DS_worklist_data", "worklist_data")

        If DS3.Tables(0).Rows.Count > 0 Then

            StrMssql2 = "DELETE FROM  worklist_data WHERE ACCESSIONNUMBER  ='" & OrderNo_data & "' "
            Mssql1.MsExecute(StrMssql2)


        End If
        '-----------------

        ' Delete MySQL-----
        iQstrSql1 = "select accessionnum from worklist where accessionnum ='" & OrderNo_data & "'  "

        iQDS1 = iQMysql.iQGetMYSQLDataset(iQstrSql1, "DS_worklist", "worklist")
        If iQDS1.Tables(0).Rows.Count > 0 Then

            iQstrSql2 = "delete from worklist where accessionnum ='" & OrderNo_data & "'   "
            iQMysql.MySQLExecute(iQstrSql2)

        End If

    End Function

    Private Function SaveDataToDB()
        Dim DS2 As New DataSet
        Dim col As String
        Dim xhosData As String

        'col = "  ACCESSIONNUMBER ,MODALITY,PATIENT_ID,PATIENTTYPE,CLINICAL_ID,FIRSTNAME,LASTNAME,PATIENTSEX, " & _
        '              " PATIENTAGE,BIRTHDATE,BEDID,PATIENTSIZE,PATIENTWEIGHT,PATIENTTELEPHONENUMBER,ADMITTINGDATE, " & _
        '              " REQUESTEDPROCEDUREDESCRIPTION,EXAMINEPART,PART_COUNT,EXAMINEFEE,EXAMINEDISCOUNT,CASE_ID,PRIORITY, " & _
        '              " REGISTEROR,UPLOAD_DATE,START_REGISTERDATE,REGISTERDATE,FILM1417,START_EXAMINEDATE,EXAMINEDATE, " & _
        '              " DIAGNOSISRESULT,CLINIC_ACCORD,REPORTDOCTOR,START_REPORTDATE,REPORTDATE,START_AUDITINGDATE,AUDITINGDATE, " & _
        '              " AUDITINGDATE1,PROF,HOSPITAL_ID,BSTATE,LASTUPDATEDATE,LASTPRINTDATE,STUDIESMEMO,REQUESTINGDEPARTMENT, " & _
        '              " REFERRINGPHYSICIAN,NATION "

        col = "  ACCESSIONNUMBER ,MODALITY,PATIENT_ID,PATIENTTYPE,CLINICAL_ID,FIRSTNAME,LASTNAME,PATIENTSEX, " & _
              " PATIENTAGE,BIRTHDATE,CID,ADDRESS,TELEPHONE,EXAMINEDATE,REGISTERDATE,EXAMINEPART,REQUESTINGDEPARTMENT, " & _
              " REFERRINGPHYSICIAN,ST_IMPORT,ST_EXPORT,ST_REPORT "



        xhosData = " '" & Me.txtOrder.Text.ToString() & "' ," & _
                          " '" & Me.txtModality.Text & "', " & _
                          " '" & Me.txtHN.Text & "', " & _
                          " '" & Me.txtPaitentType.Text & "' ," & _
                          " '" & Me.txtOrder.Text.ToString() & "', " & _
                          " '" & HL7ReserverClear(Me.txtName.Text) & "' ," & _
                          " '" & HL7ReserverClear(Me.txtName.Text) & "' ," & _
                          " '" & Me.txtSex.Text & "' ," & _
                          " '" & Me.txtAge.Text & "', " & _
                          " '" & MsDate(strHL7Date2Date(txtBirthdate.Text)) & "' ," & _
                          " '" & Me.txtCID.Text & "' ," & _
                          " '" & Me.txtAddress.Text & "' ," & _
                          " '" & Me.txtTelephone.Text & "' ," & _
                          " '" & MsDate(strHL7Date2Date(Me.txtOrderDateTime.Text)) & "' ," & _
                          " '" & MsDateTime(strHL7Date2Date(Me.txtOrderDateTime.Text), strHL7DateTime2Time(Me.txtOrderDateTime.Text)) & "' ," & _
                          " '" & HL7ReserverClear(Me.txtOrderTypeName.Text) & "' ," & _
                          " '" & Me.txtOrderDep.Text & "' ," & _
                          " '" & HL7ReserverClear(Me.txtDoctorOrder.Text) & "' ," & _
                          " '" & 1 & "' ," & _
                          " '" & 0 & "' ," & _
                          " '" & 0 & "' "

        '----------------------------------------------------------------

        StrMssql = "select ACCESSIONNUMBER from worklist_data where ACCESSIONNUMBER ='" & Me.txtOrder.Text & "' "

        DS2 = Mssql1.GetMSSQLDataset(StrMssql, "DS_worklist_data", "worklist_data")

        If DS2.Tables(0).Rows.Count <= 0 Then

            StrMssql = "INSERT INTO worklist_data (" & col & ")" & _
                       "  VALUES(" & xhosData & ")"
            Mssql1.MsExecute(StrMssql)

            '---UP xray_PACK 
            'UpXray_pacs(DS2.Tables(0).Rows(0).Item("xn").ToString())
            '---------------

            'Me.txtConsole.Text = "XN= " & DS1.Tables(0).Rows(i).Item("xn").ToString() & "  HN= " & DS1.Tables(0).Rows(i).Item("hn").ToString() & " PT=  " & DS1.Tables(0).Rows(i).Item("ptname").ToString() & " Exam.=  " & DS1.Tables(0).Rows(i).Item("xray_name").ToString() & vbNewLine & Me.txtConsole.Text
            '--------------
            'DaySrearch()
            '--------------

            Export2GDT()

            '--------------

        End If


    End Function

    Private Sub Export2GDT()
        If chkEx2GDT.Checked Then

            'Me.txtConsole.Text = ""
            'Me.txtAge.Text = ""
            'Me.txtDoctorOrder.Text = ""
            'Me.txtHN.Text = ""
            'Me.txtModality.Text = ""
            'Me.txtName.Text = ""
            'Me.txtOrder.Text = ""
            'Me.txtOrderDateTime.Text = ""
            'Me.txtOrderDep.Text = ""
            'Me.txtOrdertype.Text = ""
            'Me.txtOrderTypeName.Text = ""
            'Me.txtSex.Text = ""

            'Dim FILE_NAME As String = ClsSQLhelper.ImportPath + DS.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString() + ".GDT"
            'Dim FILE_NAME As String = "D:\DD\" + DS.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString() + ".GDT"
            'Dim FILE_NAME As String = "X:\" + DS.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString() + ".txt"
            Dim FILE_NAME_GDTExport As String = ClsSQLhelper.ExportPath + Me.txtOrder.Text + ".txt"
            Dim i As Integer
            Dim aryText(28) As String

            aryText(0) = "[RecordNum1]"
            If chkiQTH2EN.Checked Then
                If (Me.txtModality.Text = "CT") Or (Me.txtModality.Text = "US") Then

                    Dim Pname As String
                    Dim ConvName As String
                    'Dim str2 As String

                    Dim Str As String = Me.txtName.Text
                    ConvName = Str.Replace(" ", "^")

                    If (Str.IndexOf("นาย", 0) <> -1) And (Str.Substring(0, 3) = "นาย") Then
                        Pname = "MR."
                        ConvName = ConvName.Replace("นาย", "")

                    ElseIf Str.IndexOf("นาง", 0) <> -1 And (Str.Substring(0, 3) = "นาง") Then
                        Pname = "MRS."
                        ConvName = ConvName.Replace("นาง", "")

                    ElseIf Str.IndexOf("น.ส.", 0) <> -1 And (Str.Substring(0, 4) = "น.ส.") Then
                        Pname = "MISS."
                        ConvName = ConvName.Replace("น.ส.", "")

                    ElseIf Str.IndexOf("นางสาว", 0) <> -1 And (Str.Substring(0, 6) = "นางสาว") Then
                        Pname = "MISS."
                        ConvName = ConvName.Replace("นางสาว", "")

                    Else
                        Pname = ""
                        ConvName = ConvName
                    End If




                    'If Trim(DS.Tables(0).Rows(0).Item("pname").ToString()) = "นาย" Then
                    '    Pname = "MR."
                    'ElseIf Trim(DS.Tables(0).Rows(0).Item("pname").ToString()) = "นาง" Then
                    '    Pname = "MRS."
                    'ElseIf Trim(DS.Tables(0).Rows(0).Item("pname").ToString()) = "น.ส." Then
                    '    Pname = "MISS."
                    'ElseIf Trim(DS.Tables(0).Rows(0).Item("pname").ToString()) = "นางสาว" Then
                    '    Pname = "MISS"
                    'ElseIf Trim(DS.Tables(0).Rows(0).Item("pname").ToString()) = "" Then
                    '    Pname = ""
                    'Else
                    '    Pname = ""
                    'End If




                    aryText(1) = "Patient Name = " + UCase(Pname & TH2R(ConvName))



                Else
                    aryText(1) = "Patient Name = " + HL7ReserverClear(Me.txtName.Text)
                End If
            Else
                aryText(1) = "Patient Name = " + HL7ReserverClear(Me.txtName.Text)
            End If
            '-------------Check CT or US Map 0206674.HN ---------------
            If (Me.txtModality.Text = "CT") Or (Me.txtModality.Text = "US") Then
                aryText(2) = "Patient ID = " + Me.txtHN.Text & ".HN"
            Else
                aryText(2) = "Patient ID = " + Me.txtHN.Text
            End If

            aryText(3) = "Date of Birth = " + strHL7Date2MsDate(txtBirthdate.Text)
            aryText(4) = "Sex = " + Me.txtSex.Text
            aryText(5) = "Accession Number = " + Me.txtOrder.Text
            aryText(6) = "Referring Physician = "
            aryText(7) = "Requesting Physician = " + Me.txtDoctorOrder.Text
            aryText(8) = "Requested Procedure ID = " + Me.txtOrder.Text
            aryText(9) = "Requested Procedure Description = "
            aryText(10) = "Requested Procedure Priority = "
            aryText(11) = "Scheduled AE Station = " + Mid(HL7ReserverClear(Me.txtOrdertype.Text), 1, 15)
            aryText(12) = "Modality = " + Me.txtModality.Text
            aryText(13) = "Scheduled Start Date = " + strHL7Date2MsDate(Me.txtOrderDateTime.Text)
            aryText(14) = "Scheduled Start Time = " + strHL7DateTime2Time(Me.txtOrderDateTime.Text)
            aryText(15) = "Performing Physician = "
            aryText(16) = "Scheduled Procedure ID = "
            aryText(17) = "Scheduled Procedure Description = "
            aryText(18) = "Scheduled Procedure Location = "
            aryText(19) = "Scheduled Procedure Pre-Medication = "
            aryText(20) = "Scheduled Procedure Contrast Agent = "
            aryText(21) = "Procedure Code Value =  " + Me.txtOrder.Text
            aryText(22) = "Procedure Code Meaning = " + Mid(HL7ReserverClear(Me.txtOrdertype.Text), 1, 40)
            aryText(23) = "Procedure Code Scheme = " + Mid(HL7ReserverClear(Me.txtOrdertype.Text), 1, 15)
            aryText(24) = "Procedure Code Scheme Version = "
            aryText(25) = "Protocol Code Value = "
            aryText(26) = "Protocol Code Meaning = "
            aryText(27) = "Protocol Code Scheme = "
            aryText(28) = "Protocol Code Scheme Version = "



            Dim objWriter As New System.IO.StreamWriter(FILE_NAME_GDTExport, False, System.Text.Encoding.GetEncoding(874))
            'Dim objWriter As New System.IO.StreamWriter(FILE_NAME)

            For i = 0 To 28

                objWriter.WriteLine(aryText(i))

            Next

            objWriter.Close()

        End If   'chkEx2GDT

    End Sub

    Private Sub GetImportData()
        'mFileName = InboxOutboxController.Instance.InboxFolder & "ORM-O01_CT_1121505246_NW.txt"
        'Me.txtConsole.Text = mFileName & vbNewLine & Me.txtConsole.Text
        '----------
        'listFile(InboxOutboxController.Instance.InboxFolder)
        listFile(ClsSQLhelper.HL7InboxPath)

    End Sub
    Private Sub GetImageData()
        Dim iQDS1 As New DataSet
        Dim DS1 As New DataSet
        Dim DS2 As New DataSet
        Dim iQstrSql1 As String
        'Dim strSql1 As String
        Dim strSql2 As String


        Dim getdate As String = MsDate(Date.Now)

        If chkConfirm.Checked Then
            'select * from worklist where status ='200' and createdate ='2013-04-23'

            iQstrSql1 = "select accessionnum " & _
              " from worklist " & _
              " where (studyuid is not null) and (status = 900 or status = 200) and date(received)  ='" & getdate & "' "

            iQDS1 = iQMysql.iQGetMYSQLDataset(iQstrSql1, "DS_worklist", "worklist")
            If iQDS1.Tables(0).Rows.Count > 0 Then
                For j = 0 To iQDS1.Tables(0).Rows.Count - 1
                    '-------------
                    'strSql1 = "select  xray_pack_status  from xray_pack  where xray_report_xn = '" & Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()) & "' and  xray_pack_status = 'N'  "
                    'DS1 = Mssql.GetMYSQLDataset(strSql1, "ds_xray_pack", "xray_pack")

                    strSql2 = "SELECT ST_EXPORT FROM worklist_data  " & _
                              " WHERE ACCESSIONNUMBER  = '" & Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()) & "' AND ST_IMPORT ='1' AND ST_EXPORT <>'1' "

                    DS1 = Mssql1.GetMSSQLDataset(strSql2, "ds_worklist_data", "worklist_data")
                    If DS1.Tables(0).Rows.Count > 0 Then
                        If DS1.Tables(0).Rows(0).Item("ST_EXPORT").ToString = "0" Then


                            strSql2 = "UPDATE worklist_data " & _
                                      " SET ST_EXPORT = '1' " & _
                                      " where ACCESSIONNUMBER = '" & Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()) & "' AND ST_IMPORT ='1'  "
                            Mssql1.MsExecute(strSql2)

                            '------------

                            Export2HL7ImageData(Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()))

                            '------------
                            Me.txtConsole.Text = "XN= " & Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()) & "  Confirm Image" & vbNewLine & Me.txtConsole.Text

                            '-------------

                        End If

                    End If


                Next j

            End If
        End If

    End Sub

    Private Sub GetReportData()
        Dim iQDS1 As New DataSet
        Dim DS1 As New DataSet
        Dim DS2 As New DataSet
        Dim iQstrSql1 As String
        'Dim strSql1 As String
        Dim strSql2 As String


        Dim getdate As String = HL7Date()

        If chkDiagReport.Checked Then
            'select * from worklist where status ='200' and createdate ='2013-04-23'

            'iQstrSql1 = "select accessionnum " & _
            '  " from worklist " & _
            '  " where (studyuid is not null) and (status = 900 or status = 200) and date(received)  ='" & getdate & "' "

            iQstrSql1 = " SELECT  s. accessionnum,r.studyUID,r.patientID,r.patientLastName,r.patientSex,r.description,CompletionFlag,VerificationFlag,ObserverOrganization,  " & _
                         " CONVERT(text_1 USING utf8) ,CONVERT(text_2 USING utf8) ,CONVERT(text_3 USING utf8) ,CONVERT(text_4 USING utf8) ,CONVERT(text_5 USING utf8)  " & _
                         " FROM iqxreports r  " & _
                         " left outer join study s on s.uuid = r.studyUID  " & _
                         " left outer join worklist w on w.accessionnum =  s. accessionnum " & _
                         " where    r. InstanceCreationDate =  '" & getdate & "'  "


            iQDS1 = iQMysql.iQGetMYSQLDataset(iQstrSql1, "DS_iqxreports", "iqxreports")
            If iQDS1.Tables(0).Rows.Count > 0 Then
                For j = 0 To iQDS1.Tables(0).Rows.Count - 1
                    '-------------
                    'strSql1 = "select  xray_pack_status  from xray_pack  where xray_report_xn = '" & Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()) & "' and  xray_pack_status = 'N'  "
                    'DS1 = Mssql.GetMYSQLDataset(strSql1, "ds_xray_pack", "xray_pack")

                    strSql2 = "SELECT ST_REPORT FROM worklist_data  " & _
                              " WHERE ACCESSIONNUMBER  = '" & Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()) & "' AND ST_IMPORT ='1' AND ST_EXPORT = '1' AND ST_REPORT <>'1'  "

                    DS1 = Mssql1.GetMSSQLDataset(strSql2, "ds_worklist_data", "worklist_data")
                    If DS1.Tables(0).Rows.Count > 0 Then
                        If DS1.Tables(0).Rows(0).Item("ST_REPORT").ToString = "0" Then


                            strSql2 = "UPDATE worklist_data " & _
                                      " SET ST_REPORT = '1' " & _
                                      " where ACCESSIONNUMBER = '" & Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()) & "' AND ST_IMPORT ='1' AND ST_EXPORT = '1' "
                            Mssql1.MsExecute(strSql2)

                            '------------

                            Export2HL7ReportData(Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()))

                            '------------
                            Me.txtConsole.Text = "XN= " & Trim(iQDS1.Tables(0).Rows(j).Item("accessionnum").ToString()) & "  Confirm Report" & vbNewLine & Me.txtConsole.Text

                            '-------------

                        End If

                    End If


                Next j

            End If
        End If

    End Sub

    Private Function Export2HL7ImageData(Order As String)
        Dim OBXaryText(3) As String
        Dim DS1 As New DataSet
        Dim strSql1 As String


        Dim ImageExport2HL7(6) As String

        Dim MSHDataTaxSegment As String = ""
        Dim PIDDataTaxSegment As String = ""
        Dim PV1DataTaxSegment As String = ""
        Dim ORCDataTaxSegment As String = ""
        Dim OBRDataTaxSegment As String = ""
        Dim OBX1DataTaxSegment As String = ""
        Dim OBX2DataTaxSegment As String = ""
        Dim FILE_NAME_Export As String = HL7OutboxPath + "ORU-R01_" + Order + ".txt"


        strSql1 = "SELECT * FROM worklist_data  " & _
                  " WHERE ACCESSIONNUMBER  = '" & Order & "' AND ST_IMPORT ='1' AND ST_EXPORT ='1'  "

        DS1 = Mssql1.GetMSSQLDataset(strSql1, "ds_worklist_data", "worklist_data")
        If DS1.Tables(0).Rows.Count > 0 Then
            FlagSegment = 1
            MSHDataTaxSegment = MSHSegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            PIDDataTaxSegment = PIDSegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            PV1DataTaxSegment = PV1SegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            ORCDataTaxSegment = ORCSegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            OBRDataTaxSegment = OBRSegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            OBX1DataTaxSegment = OBX1SegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            OBX2DataTaxSegment = OBX2SegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            FlagSegment = 0
        End If

        ' Export Confirm IMAGE 

        Dim objWriter As New System.IO.StreamWriter(FILE_NAME_Export, False, System.Text.Encoding.GetEncoding(874))

        objWriter.WriteLine(MSHDataTaxSegment)
        objWriter.WriteLine(PIDDataTaxSegment)
        objWriter.WriteLine(PV1DataTaxSegment)
        objWriter.WriteLine(ORCDataTaxSegment)
        objWriter.WriteLine(OBRDataTaxSegment)
        objWriter.WriteLine(OBX1DataTaxSegment)
        objWriter.WriteLine(OBX2DataTaxSegment)

        objWriter.Close()

        'txtConsole.Text = MSHDataTaxSegment & vbNewLine & PIDDataTaxSegment & vbNewLine & PV1DataTaxSegment & vbNewLine & ORCDataTaxSegment & vbNewLine & OBRDataTaxSegment & vbNewLine & OBX1DataTaxSegment & vbNewLine & OBX2DataTaxSegment

    End Function

    Private Function Export2HL7ReportData(Order As String)
        Dim OBXaryText(3) As String
        Dim DS1 As New DataSet
        Dim strSql1 As String
        Dim iQDS2 As New DataSet
        Dim iQstrSql2 As String


        Dim ImageExport2HL7(6) As String
        Dim OBX3aryText(16) As String
        Dim OBX3Data As String = ""

        Dim MSHDataTaxSegment As String = ""
        Dim PIDDataTaxSegment As String = ""
        Dim PV1DataTaxSegment As String = ""
        Dim ORCDataTaxSegment As String = ""
        Dim OBRDataTaxSegment As String = ""
        Dim OBX1DataTaxSegment As String = ""

        Dim FILE_NAME_HL7Report As String = HL7OutboxPath + "ORU-R02_" + Order + ".txt"


        strSql1 = "SELECT * FROM worklist_data  " & _
                  " WHERE ACCESSIONNUMBER  = '" & Order & "' AND ST_IMPORT ='1' AND ST_EXPORT ='1'  "

        DS1 = Mssql1.GetMSSQLDataset(strSql1, "ds_worklist_data", "worklist_data")
        If DS1.Tables(0).Rows.Count > 0 Then
            FlagSegment = 2

            MSHDataTaxSegment = MSHSegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            PIDDataTaxSegment = PIDSegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            PV1DataTaxSegment = PV1SegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            ORCDataTaxSegment = ORCSegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)
            OBRDataTaxSegment = OBRSegmentData(DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString)

            '------------------------------------
            OBX3aryText(0) = "OBX"
            OBX3aryText(1) = "1"
            OBX3aryText(2) = "TX"
            OBX3aryText(3) = ""
            OBX3aryText(4) = "3"

            'OBX3aryText(5) = "\.br\Report Status: PRELIMINARY\.br\\.br\Name: PATIENT, TEST M\.br\MRN: P12345\.br\DOB: 10/18/1974\.br\PHONE: (909)481-5800\.br\Referring Physician: JONES, SAMUEL MD\.br\DOS: 2/23/2011 8:00:00 AM\.br\THYROID ULTRASOUND:\.br\INDICATIONS:  Multi-nodular goiter.  Compare to prior studies.\.br\\.br\Comparison is made to 2/12/08.\.br\\.br\The thyroid gland is within normal limits of size.  The right lobe measures 4.4 x 1.2 x 2.0cm.  The left lobe measures 4.8 x 1.4 x 1.4cm.  Several small nodules are seen in each lobe.  There appears to be a new nodule in the left lobe inferior aspect measuring 0.5cm. \.br\\.br\IMPRESSION:\.br\A few small thyroid nodules are seen bilaterally.  There is a one new 0.5cm. Nodule in the left lobe inferiorly.\.br\\.br\Radiologist:  PATEL, APU MD\.br\\.br\Accession: A123456\.br\Consulting Physicians: SMITH\S\JOHN MD, JONES\S\SAMUEL MD \.br\Transcribed by:  ET\.br\2/23/2011 10:12:25 AM"
            'OBX3aryText(5) = ''
            '--------------------------------------
            iQstrSql2 = " SELECT  s. accessionnum,r.studyUID,r.patientID,r.patientLastName,r.patientSex,r.description,CompletionFlag,VerificationFlag,ObserverOrganization,  " & _
                        " CONVERT(text_1 USING utf8)as text1 ,CONVERT(text_2 USING utf8)as text2 ,CONVERT(text_3 USING utf8)as text3 ,CONVERT(text_4 USING utf8)as text4 ,CONVERT(text_5 USING utf8)as text5,  " & _
                        " r.description,StudyDescription,ObserverOrganization,ObserverName,InstanceCreationDate,InstanceCreationTime  " & _
                        " FROM iqxreports r  " & _
                        " left outer join study s on s.uuid = r.studyUID  " & _
                        " left outer join worklist w on w.accessionnum =  s. accessionnum " & _
                        " where    s. accessionnum =  '" & DS1.Tables(0).Rows(0).Item("ACCESSIONNUMBER").ToString & "'  "

            iQDS2 = iQMysql.iQGetMYSQLDataset(iQstrSql2, "DS_iqxreports", "iqxreports")
            If iQDS2.Tables(0).Rows.Count > 0 Then

                OBX3aryText(5) = "Request No. : " + iQDS2.Tables(0).Rows(0).Item("accessionnum").ToString() & _
                                 " HN : " + iQDS2.Tables(0).Rows(0).Item("patientID").ToString() & _
                                 " ชื่อ : " + EncodeString(iQDS2.Tables(0).Rows(0).Item("patientLastName").ToString()) & _
                                 "\.br\" & " StudyDescription : " + iQDS2.Tables(0).Rows(0).Item("StudyDescription").ToString() & _
                                 "\.br\" & " Hospital : " + iQDS2.Tables(0).Rows(0).Item("ObserverOrganization").ToString() & _
                                 "\.br\" & " ReportDateTime : " + strHL7Date2Date(iQDS2.Tables(0).Rows(0).Item("InstanceCreationDate").ToString()) + " " + iQDS2.Tables(0).Rows(0).Item("InstanceCreationTime").ToString()


                OBX3aryText(5) = OBX3aryText(5) & "\.br\" & "Report :" & "\.br\" & EncodeString(iQDS2.Tables(0).Rows(0).Item("description").ToString) & _
                                  "\.br\" & "History :" & "\.br\" & ConvertRtfToText(iQDS2.Tables(0).Rows(0).Item("text1").ToString) & _
                                  "\.br\" & "Request :" & "\.br\" & ConvertRtfToText(iQDS2.Tables(0).Rows(0).Item("text2").ToString) & _
                                  "\.br\" & "Finding :" & "\.br\" & ConvertRtfToText(iQDS2.Tables(0).Rows(0).Item("text3").ToString) & _
                                  "\.br\" & "Impression :" & "\.br\" & ConvertRtfToText(iQDS2.Tables(0).Rows(0).Item("text4").ToString) & _
                                  "\.br\" & "Reccommendation :" & "\.br\" & ConvertRtfToText(iQDS2.Tables(0).Rows(0).Item("text5").ToString) & _
                                  "\.br\" & _
                                  "\.br\" & EncodeString(iQDS2.Tables(0).Rows(0).Item("ObserverName").ToString)



            End If
            '--------------------------------------

            OBX3aryText(6) = ""
            OBX3aryText(7) = ""
            OBX3aryText(8) = ""
            OBX3aryText(9) = ""
            OBX3aryText(10) = ""
            OBX3aryText(11) = "F"
            OBX3aryText(12) = ""
            OBX3aryText(13) = ""
            OBX3aryText(14) = MsDateTimeFull(Now())
            OBX3aryText(15) = ""
            OBX3aryText(16) = ""



        End If

        OBX3Data = OBX3aryText(0)

        For i = 1 To 16

            OBX3Data = OBX3Data & "|" & OBX3aryText(i)

        Next

        OBX1DataTaxSegment = OBX3Data

        FlagSegment = 0


        ' Export Report Data 
        Dim objWriter As New System.IO.StreamWriter(FILE_NAME_HL7Report, False, System.Text.Encoding.GetEncoding(874))

        objWriter.WriteLine(MSHDataTaxSegment)
        objWriter.WriteLine(PIDDataTaxSegment)
        objWriter.WriteLine(PV1DataTaxSegment)
        objWriter.WriteLine(ORCDataTaxSegment)
        objWriter.WriteLine(OBRDataTaxSegment)
        objWriter.WriteLine(OBX1DataTaxSegment)



        objWriter.Close()

        'txtConsole.Text = MSHDataTaxSegment & vbNewLine & PIDDataTaxSegment & vbNewLine & PV1DataTaxSegment & vbNewLine & ORCDataTaxSegment & vbNewLine & OBRDataTaxSegment & vbNewLine & OBX1DataTaxSegment & vbNewLine & OBX2DataTaxSegment

    End Function

    Public Shared Function ConvertRtfToText(ByVal input As String) As String
        Dim returnValue As String = String.Empty
        Using converter As New System.Windows.Forms.RichTextBox()
            converter.Rtf = input
            returnValue = converter.Text
        End Using
        Return returnValue
    End Function




    Private Function MSHSegmentData(Order As String) As String
        Dim i As Integer
        Dim MSHaryText(19) As String
        Dim MSHData As String = ""
        Dim PIDData As String = ""


        'MSH|^~\&|AKISSOFT|XRAY|PACS|PACS|20111206174303||ORU^R01|111880813|P|2.3|||AL|NE|TH||

        MSHaryText(0) = "MSH"
        MSHaryText(1) = "^~\&"
        MSHaryText(2) = "AKISSOFT"
        MSHaryText(3) = "XRAY"
        MSHaryText(4) = "PACS"
        MSHaryText(5) = "PACS"
        MSHaryText(6) = HL7DateTime()
        MSHaryText(7) = ""

        If FlagSegment = 1 Then
            MSHaryText(8) = "ORU^R01"
        ElseIf FlagSegment = 2 Then
            MSHaryText(8) = "ORU^R02"
        End If

        MSHaryText(9) = Order
        MSHaryText(10) = "P"
        MSHaryText(11) = "2.3"
        MSHaryText(12) = "MSH"
        MSHaryText(13) = ""
        MSHaryText(14) = ""
        MSHaryText(15) = "AL"
        MSHaryText(16) = "NE"
        MSHaryText(17) = "TH"
        MSHaryText(18) = ""

        MSHData = MSHaryText(0)
        For i = 1 To 18

            MSHData = MSHData & "|" & MSHaryText(i)

        Next

        Return MSHData


    End Function
    Private Function PIDSegmentData(Order As String) As String
        Dim DSs As New DataSet
        Dim strSqls As String
        Dim i As Integer
        Dim PIDaryText(29) As String
        Dim PIDData As String = ""

        strSqls = "SELECT * FROM worklist_data  " & _
                  " WHERE ACCESSIONNUMBER  = '" & Order & "' AND ST_IMPORT ='1' AND ST_EXPORT ='1'  "

        DSs = Mssql1.GetMSSQLDataset(strSqls, "ds_worklist_data", "worklist_data")
        If DSs.Tables(0).Rows.Count > 0 Then
            '                                        7            8   11             13                                              18
            'PID|1||4302628||น.ส.พิมพ์นิภา ฐิติชัยวรภัทร||19650416000000|F|||224 ม. 1^^^^^||054-352833,089-4330980^054-352833,089-43309|||||3521000174140||||||||||||

            PIDaryText(0) = "PID"
            PIDaryText(1) = "1"
            PIDaryText(2) = ""
            PIDaryText(3) = DSs.Tables(0).Rows(0).Item("PATIENT_ID").ToString
            PIDaryText(4) = ""
            PIDaryText(5) = DSs.Tables(0).Rows(0).Item("FIRSTNAME").ToString
            PIDaryText(6) = ""
            PIDaryText(7) = MsDateFull(DSs.Tables(0).Rows(0).Item("BIRTHDATE").ToString)
            PIDaryText(8) = DSs.Tables(0).Rows(0).Item("PATIENTSEX").ToString
            PIDaryText(9) = ""
            PIDaryText(10) = ""
            PIDaryText(11) = DSs.Tables(0).Rows(0).Item("ADDRESS").ToString
            PIDaryText(12) = ""
            PIDaryText(13) = DSs.Tables(0).Rows(0).Item("TELEPHONE").ToString
            PIDaryText(14) = ""
            PIDaryText(15) = ""
            PIDaryText(16) = ""
            PIDaryText(17) = ""
            PIDaryText(18) = DSs.Tables(0).Rows(0).Item("CID").ToString
            PIDaryText(19) = ""
            PIDaryText(20) = ""
            PIDaryText(21) = ""
            PIDaryText(22) = ""
            PIDaryText(23) = ""
            PIDaryText(24) = ""
            PIDaryText(25) = ""
            PIDaryText(26) = ""
            PIDaryText(27) = ""
            PIDaryText(28) = ""
            PIDaryText(29) = ""

        End If

        PIDData = PIDaryText(0)

        For i = 1 To 29

            PIDData = PIDData & "|" & PIDaryText(i)

        Next

        Return PIDData


    End Function

    Private Function PV1SegmentData(Order As String) As String
        Dim DS3 As New DataSet
        Dim strSql3 As String
        Dim i As Integer
        Dim PV1aryText(8) As String
        Dim PV1Data As String = ""

        strSql3 = "SELECT * FROM worklist_data  " & _
                  " WHERE ACCESSIONNUMBER  = '" & Order & "' AND ST_IMPORT ='1' AND ST_EXPORT ='1'  "

        DS3 = Mssql1.GetMSSQLDataset(strSql3, "ds_worklist_data", "worklist_data")
        If DS3.Tables(0).Rows.Count > 0 Then
            '         3           7                                                                
            'PV1|1|O|^^OPD-C1||||^วัฒนเชษฐ์^พิเชษฐ์^น.พ.|||||||||||||||||||||||||||||||||||||||||||||

            PV1aryText(0) = "PV1"
            PV1aryText(1) = "1"
            PV1aryText(2) = "O"
            PV1aryText(3) = DS3.Tables(0).Rows(0).Item("REQUESTINGDEPARTMENT").ToString
            PV1aryText(4) = ""
            PV1aryText(5) = ""
            PV1aryText(6) = ""
            PV1aryText(7) = DS3.Tables(0).Rows(0).Item("REFERRINGPHYSICIAN").ToString
            PV1aryText(8) = "|||||||||||||||||||||||||||||||||||||||||||||"


        End If

        PV1Data = PV1aryText(0)

        For i = 1 To 8

            PV1Data = PV1Data & "|" & PV1aryText(i)

        Next

        Return PV1Data


    End Function

    Private Function ORCSegmentData(Order As String) As String
        Dim DS4 As New DataSet
        Dim strSql4 As String
        Dim i As Integer
        Dim ORCaryText(13) As String
        Dim ORCData As String = ""

        strSql4 = "SELECT * FROM worklist_data  " & _
                  " WHERE ACCESSIONNUMBER  = '" & Order & "' AND ST_IMPORT ='1' AND ST_EXPORT ='1'  "

        DS4 = Mssql1.GetMSSQLDataset(strSql4, "ds_worklist_data", "worklist_data")
        If DS4.Tables(0).Rows.Count > 0 Then
            '        2           5     9                  12                                                 
            'ORC|NW|111880813|||SC||||20111206184303|||น.พ.พิเชษฐ์  วัฒนเชษฐ์|||||||

            ORCaryText(0) = "ORC"
            ORCaryText(1) = "NW"
            ORCaryText(2) = Order
            ORCaryText(3) = DS4.Tables(0).Rows(0).Item("REQUESTINGDEPARTMENT").ToString
            ORCaryText(4) = ""
            ORCaryText(5) = "SC"
            ORCaryText(6) = ""
            ORCaryText(7) = ""
            ORCaryText(8) = ""
            ORCaryText(9) = MsDateTimeFull(DS4.Tables(0).Rows(0).Item("REGISTERDATE").ToString)
            ORCaryText(10) = ""
            ORCaryText(11) = ""
            ORCaryText(12) = DS4.Tables(0).Rows(0).Item("REFERRINGPHYSICIAN").ToString
            ORCaryText(13) = "|||||||"


        End If

        ORCData = ORCaryText(0)

        For i = 1 To 13

            ORCData = ORCData & "|" & ORCaryText(i)

        Next

        Return ORCData


    End Function

    Private Function OBRSegmentData(Order As String) As String
        Dim DS5 As New DataSet
        Dim strSql5 As String
        Dim i As Integer
        Dim OBRaryText(17) As String
        Dim OBRData As String = ""

        strSql5 = "SELECT * FROM worklist_data  " & _
                  " WHERE ACCESSIONNUMBER  = '" & Order & "' AND ST_IMPORT ='1' AND ST_EXPORT ='1'  "

        DS5 = Mssql1.GetMSSQLDataset(strSql5, "ds_worklist_data", "worklist_data")
        If DS5.Tables(0).Rows.Count > 0 Then
            '        2           4                                  6                 13    16               
            'OBR|1|111880813||X0503^CHEST  AP,LAT^CHEST  AP,LAT||20111206194303|||||||CR|||น.พ.  พิเชษฐ์  วัฒนเชษฐ์|||||||||||||||||||||||||||

            OBRaryText(0) = "OBR"
            OBRaryText(1) = "1"
            OBRaryText(2) = Order
            OBRaryText(3) = ""
            OBRaryText(4) = DS5.Tables(0).Rows(0).Item("EXAMINEPART").ToString
            OBRaryText(5) = ""
            OBRaryText(6) = MsDateTimeFull(DS5.Tables(0).Rows(0).Item("REGISTERDATE").ToString)
            OBRaryText(7) = ""
            OBRaryText(8) = ""
            OBRaryText(9) = ""
            OBRaryText(10) = ""
            OBRaryText(11) = ""
            OBRaryText(12) = ""
            OBRaryText(13) = DS5.Tables(0).Rows(0).Item("MODALITY").ToString
            OBRaryText(14) = ""
            OBRaryText(15) = ""
            OBRaryText(16) = DS5.Tables(0).Rows(0).Item("REFERRINGPHYSICIAN").ToString
            OBRaryText(17) = "|||||||||||||||||||||||||||"


        End If

        OBRData = OBRaryText(0)

        For i = 1 To 17

            OBRData = OBRData & "|" & OBRaryText(i)

        Next

        Return OBRData


    End Function


    Private Function OBX1SegmentData(Order As String) As String
        Dim DS6 As New DataSet
        Dim strSql6 As String
        Dim i As Integer
        Dim OBX1aryText(16) As String
        Dim OBX1Data As String = ""

        Dim iQDS3 As New DataSet
        Dim iQstrSql3 As String

        Dim WadoOrder As String = ""

        strSql6 = "SELECT * FROM worklist_data  " & _
                  " WHERE ACCESSIONNUMBER  = '" & Order & "' AND ST_IMPORT ='1' AND ST_EXPORT ='1'  "

        DS6 = Mssql1.GetMSSQLDataset(strSql6, "ds_worklist_data", "worklist_data")
        If DS6.Tables(0).Rows.Count > 0 Then
            '-------------------------------------
            iQstrSql3 = "select studyuid  from worklist where accessionnum ='" & Order & "'  "

            iQDS3 = iQMysql.iQGetMYSQLDataset(iQstrSql3, "DS_worklist", "worklist")
            If iQDS3.Tables(0).Rows.Count > 0 Then


                'RedirectStr = "http://192.168.1.231:9000/pacs/wado.php?mode=2&id_1=" & dt.Rows(0)("studyuid") & "&iq_x=1&header_off=1&username=d3bcf609b91f4a348361a2ba7216912af57c487e398797fd544630cca6139031&password=fdf45c9cede41918e92fcaf9c13a43801b163c84be42e6698c6444b51ce85fba&lltt=f735facfef6dbbc9cad52f6103def647ccd6b43d6e963130cc46db56f98c38c9"

                'Dim WadoOrder As String = WadoServ & "pacs/wado.php?mode=4\T\id_1=" & Order & "\T\header_off=1\T\username=" & WadoUsername & "\T\password=" & WadoPassword & "\T\lltt=" & WadoTTL
                ' WadoOrder = WadoServ & "pacs/wado.php?mode=2\T\id_1=" & iQDS3.Tables(0).Rows(0).Item("studyuid").ToString() & "\T\iq_x=1\T\header_off=1\T\username=" & WadoUsername & "\T\password=" & WadoPassword & "\T\lltt=" & WadoTTL
                WadoOrder = WadoServ & "pacs/wado.php?mode=2&id_1=" & iQDS3.Tables(0).Rows(0).Item("studyuid").ToString() & "&iq_x=1&header_off=1&username=" & WadoUsername & "&password=" & WadoPassword & "&lltt=" & WadoTTL


            End If
            '----------------------------------------


            '       2           3                           4       5                                                                                                                                                                                                                                                                                                11 13            14
            'OBX|1|TX|X0503^CHEST  AP,LAT^CHEST  AP,LAT^^^1|1|http://localhost/pacs/wado.php?mode=4\T\id_1=1234\T\iq_x=1\T\header_off=1\T\username=d3bcf609b91f4a348361a2ba7216912af57c487e398797fd544630cca6139031\T\password=fdf45c9cede41918e92fcaf9c13a43801b163c84be42e6698c6444b51ce85fba\T\lltt=ef324e0d51087715bed59441812e93bf99833c8e58faab7484af31ea811913fd ||||||F||Porttable |20111206184003|||

            OBX1aryText(0) = "OBX"
            OBX1aryText(1) = "1"
            OBX1aryText(2) = "TX"
            OBX1aryText(3) = DS6.Tables(0).Rows(0).Item("EXAMINEPART").ToString
            OBX1aryText(4) = "1"
            OBX1aryText(5) = WadoOrder
            OBX1aryText(6) = ""
            OBX1aryText(7) = ""
            OBX1aryText(8) = ""
            OBX1aryText(9) = ""
            OBX1aryText(10) = ""
            OBX1aryText(11) = "F"
            OBX1aryText(12) = ""
            OBX1aryText(13) = ""
            OBX1aryText(14) = MsDateTimeFull(Now())
            OBX1aryText(15) = ""
            OBX1aryText(16) = ""



        End If

        OBX1Data = OBX1aryText(0)

        For i = 1 To 16

            OBX1Data = OBX1Data & "|" & OBX1aryText(i)

        Next

        Return OBX1Data


    End Function

    Private Function OBX2SegmentData(Order As String) As String
        Dim DS7 As New DataSet
        Dim strSql7 As String
        Dim i As Integer
        Dim OBX2aryText(16) As String
        Dim OBX2Data As String = ""

        strSql7 = "SELECT * FROM worklist_data  " & _
                  " WHERE ACCESSIONNUMBER  = '" & Order & "' AND ST_IMPORT ='1' AND ST_EXPORT ='1'  "

        DS7 = Mssql1.GetMSSQLDataset(strSql7, "ds_worklist_data", "worklist_data")
        If DS7.Tables(0).Rows.Count > 0 Then

            'Dim WadoOrder As String = WadoServ & "pacs/wado.php?mode=1\T\id_1=" & DS7.Tables(0).Rows(0).Item("PATIENT_ID").ToString & "\T\header_off=1\T\username=" & WadoUsername & "\T\password=" & WadoPassword & "\T\lltt=" & WadoTTL
            Dim WadoOrder As String = WadoServ & "pacs/wado.php?mode=1&id_1=" & DS7.Tables(0).Rows(0).Item("PATIENT_ID").ToString & "*&header_off=1&username=" & WadoUsername & "&password=" & WadoPassword & "&lltt=" & WadoTTL

            '       2           3                           4       5                                                                                                                                                                                                                                                                                                11 13            14
            'OBX|1|TX|X0503^CHEST  AP,LAT^CHEST  AP,LAT^^^1|1|http://localhost/pacs/wado.php?mode=4\T\id_1=1234\T\header_off=1\T\username=d3bcf609b91f4a348361a2ba7216912af57c487e398797fd544630cca6139031\T\password=fdf45c9cede41918e92fcaf9c13a43801b163c84be42e6698c6444b51ce85fba\T\lltt=ef324e0d51087715bed59441812e93bf99833c8e58faab7484af31ea811913fd ||||||F||Porttable |20111206184003|||

            OBX2aryText(0) = "OBX"
            OBX2aryText(1) = "2"
            OBX2aryText(2) = "TX"
            OBX2aryText(3) = DS7.Tables(0).Rows(0).Item("EXAMINEPART").ToString
            OBX2aryText(4) = "2"
            OBX2aryText(5) = WadoOrder
            OBX2aryText(6) =
            OBX2aryText(7) = ""
            OBX2aryText(8) = ""
            OBX2aryText(9) = ""
            OBX2aryText(10) = ""
            OBX2aryText(11) = "F"
            OBX2aryText(12) = ""
            OBX2aryText(13) = ""
            OBX2aryText(14) = MsDateTimeFull(Now())
            OBX2aryText(15) = ""
            OBX2aryText(16) = ""



        End If

        OBX2Data = OBX2aryText(0)

        For i = 1 To 16

            OBX2Data = OBX2Data & "|" & OBX2aryText(i)

        Next

        Return OBX2Data


    End Function

    Private Sub cmdGetdata_Click(sender As System.Object, e As System.EventArgs) Handles cmdGetdata.Click
        'RichTextData.Text = HL7Helper_Get.getValue(RichTextHL7.Text, "PID", 7, 0, 0)
        'mFileName = InboxOutboxController.Instance.InboxFolder & "ORM-O01_CR_111880813_NW.HL7"
        mFileName = InboxOutboxController.Instance.InboxFolder & "ORM-O01_CT_1121505246_NW.txt"

        ReadFile(mFileName)

        'Me.RichTextData.Text = IO.Path.GetFileName(ssPath)
        'Me.RichTextData.Text = ssPath & Me.RichTextData.Text

    End Sub

    Private Sub ReadFile(ReadFileName As String)

        SyncLock Me

            Try

                If IO.File.Exists(ReadFileName) Then

                    Me.mLines.Clear()

                    ' Create an instance of StreamWriter to write text to a file.
                    Dim sr As StreamReader = New StreamReader(ReadFileName, System.Text.Encoding.GetEncoding(874))

                    Try

                        Do While sr.Peek >= 0

                            ' Add some text to the file.
                            Dim Line As String = sr.ReadLine()


                            If Line.Length >= 3 Then


                                'HL7Objects.HL7.Delims(Line.ToString)
                                Dim SSdata As String = HL7.ToSegmentType(Line.ToString)



                                Select Case SSdata

                                    Case SegmentType_.MSH

                                        Me.txtOrder.Text = HL7Helper_Get.getValue(Line.ToString, "MSH", 10, 0, 0)

                                        'HL7Objects.HL7.Delims(Line.ToString)

                                        'Me.txtConsole.Text = "----MSH----"

                                        'Dim strDataGet(19) As String

                                        'Dim dataGet As String = ""

                                        'For i As Integer = 1 To 19

                                        'Dim sdataGet As String = HL7Helper_Get.getValue(Line.ToString, "MSH", i, 0, 0)

                                        'strDataGet(i - 1) = dataGet

                                        'DataGridViewX1.Rows.Add(sdataGet)

                                        'If dataGet = "" Then

                                        '    dataGet = Chr(34) & sdataGet & Chr(34) & ","

                                        'Else

                                        '    dataGet = dataGet & Chr(34) & sdataGet & Chr(34) & ","

                                        'End If

                                        'Me.txtConsole.Text = dataGet & vbNewLine & Me.txtConsole.Text



                                        'Next i

                                        'dataGet = LTrim(dataGet)

                                        'Dim row As String() = New String() {"aaaa", "Product 1", "1000"}

                                        'Dim row As String() = New String() {dataGet}

                                        'DataGridViewX1.Rows.Add(row)

                                        'For j As Integer = 0 To 19 - 1

                                        '    dataGet = dataGet & strDataGet(j - 1)

                                        'Next j

                                        'Dim row As String() = New String() {dataGet}
                                        'DataGridViewX1.Rows.Add(row)

                                    Case SegmentType_.PID

                                        'HN หลักที่ 4
                                        Me.txtHN.Text = HL7Helper_Get.getValue(Line.ToString, "PID", 4, 0, 0)
                                        Me.txtName.Text = HL7Helper_Get.getValue(Line.ToString, "PID", 6, 0, 0)
                                        Me.txtBirthdate.Text = HL7Helper_Get.getValue(Line.ToString, "PID", 8, 0, 0)
                                        Me.txtAge.Text = CalculateAge(HL7Helper_Get.getValue(Line.ToString, "PID", 8, 0, 0))
                                        Me.txtSex.Text = HL7Helper_Get.getValue(Line.ToString, "PID", 9, 0, 0)
                                        Me.txtAddress.Text = HL7Helper_Get.getValue(Line.ToString, "PID", 12, 0, 0)
                                        Me.txtTelephone.Text = HL7Helper_Get.getValue(Line.ToString, "PID", 14, 0, 0)
                                        Me.txtCID.Text = HL7Helper_Get.getValue(Line.ToString, "PID", 19, 0, 0)
                                        'Me.txtConsole.Text = "PID" & vbNewLine & Me.txtConsole.Text

                                    Case SegmentType_.ORC
                                        Me.txtData_Type.Text = HL7Helper_Get.getValue(Line.ToString, "ORC", 2, 0, 0)
                                        Me.txtOrderDateTime.Text = HL7Helper_Get.getValue(Line.ToString, "ORC", 10, 0, 0)
                                        'Me.txtConsole.Text = "ORC" & vbNewLine & Me.txtConsole.Text

                                    Case SegmentType_.OBR
                                        Me.txtOrderTypeName.Text = HL7Helper_Get.getValue(Line.ToString, "OBR", 5, 0, 0)
                                        Me.txtOrdertype.Text = HL7Helper_Get.getValue(Line.ToString, "OBR", 4, 2, 0)
                                        Me.txtModality.Text = HL7Helper_Get.getValue(Line.ToString, "OBR", 14, 0, 0)
                                        Me.txtDoctorOrder.Text = HL7Helper_Get.getValue(Line.ToString, "OBR", 17, 0, 0)
                                        'Me.txtConsole.Text = "OBR" & vbNewLine & Me.txtConsole.Text

                                    Case SegmentType_.OBX

                                        'Me.txtConsole.Text = "OBX" & vbNewLine & Me.txtConsole.Text

                                    Case SegmentType_.NTE

                                        'Me.txtConsole.Text = "NTE" & vbNewLine & Me.txtConsole.Text


                                    Case SegmentType_.ZPS

                                        'Me.txtConsole.Text = "ZPS" & vbNewLine & Me.txtConsole.Text

                                    Case SegmentType_.ADD

                                        'Me.txtConsole.Text = "ADD" & vbNewLine & Me.txtConsole.Text

                                    Case SegmentType_.UNK

                                        'Me.txtConsole.Text = "UNK" & vbNewLine & Me.txtConsole.Text

                                        Me.txtOrderDep.Text = HL7Helper_Get.getValue(Line.ToString, "PV1", 4, 0, 0)
                                        Me.txtPaitentType.Text = HL7Helper_Get.getValue(Line.ToString, "PV1", 3, 0, 0)

                                        'Case SegmentType_.PV1

                                        '    Me.txtConsole.Text = "UNK" & vbNewLine & Me.txtConsole.Text


                                    Case Else



                                End Select
                            End If


                        Loop


                        'txtFileName.Text = mFileName
                        txtFileName.Text = ReadFileName
                    Catch ex As Exception

                        Throw ex

                    Finally

                        sr.Close()

                    End Try

                End If

            Catch ex As Exception

                Throw ex

            End Try

        End SyncLock

    End Sub

    Private Function MakeTextLineObject(ByVal pKey As String, ByVal pClassName As String, ByVal pData As String) As iTextLine

        Dim TL As iTextLine = ConstructClass(pClassName)

        If Not TL Is Nothing Then

            TL.Key = pKey
            TL.DecodeData(pData)

        End If

        Return TL

    End Function

    Private Function ConstructClass(ByVal pClassName As String) As iTextLine

        Select Case pClassName

            Case "jKeyStringPair"

                Return New jKeyStringPair

            Case "jKeyIntegerPair"

                Return New jKeyIntegerPair

            Case "jKeyBooleanPair"

                Return New jKeyBooleanPair

            Case Else

                Return Nothing

        End Select

    End Function

    Private Sub DataGridViewX1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs)

    End Sub



    Sub Main()
        Dim text As String = EncodeString("ä·Â")  'ไทย
    End Sub

    Function EncodeString(ByRef Str As String)
        Dim latinEnc As System.Text.Encoding = System.Text.Encoding.GetEncoding("iso-8859-1")
        'Dim thaiEnc As System.Text.Encoding = System.Text.Encoding.GetEncoding("TIS-620")
        Dim thaiEnc As System.Text.Encoding = System.Text.Encoding.GetEncoding(874)
        Dim bytes As Byte() = latinEnc.GetBytes(Str)
        Dim textResult As String = thaiEnc.GetString(bytes)
        Return textResult


    End Function

    Public utf8 As Encoding = Encoding.UTF8
    Public ascii As Encoding = Encoding.Default
    Public latin1 As Encoding = Encoding.Unicode


    Public Function Utf8ToAscii(ByVal DataString As String) As String
        If DataString = "" Then Return "" Else 
        Utf8ToAscii = utf8.GetString(ascii.GetBytes(DataString))

    End Function

    Public Function AsciiToUtf8(ByVal DataString As String) As String
        If DataString = "" Then Return "" Else 
        AsciiToUtf8 = ascii.GetString(utf8.GetBytes(DataString))

    End Function
    Public Function AsciiToUnicode(ByVal DataString As String) As String
        If DataString = "" Then Return "" Else 
        'AsciiToUnicode = ascii.GetString(utf8.GetBytes(DataString))
        AsciiToUnicode = ascii.GetString(Encoding.Unicode.GetBytes(DataString))


    End Function

    Private Function CalculateAge(Sdate As String) As String
        Dim ADate As String
        ADate = Mid(Sdate, 7, 2) & "/" & Mid(Sdate, 5, 2) & "/" & Int(Mid(Sdate, 1, 4)) + 543

        Dim Birth As Date = ADate
        Dim year, month, day As Integer
        While year <= (Now.Year - Birth.Year)
            While month <= (Now.Month - Birth.Month)
                While day <= (Now.Day - Birth.Day)
                    day += 1
                End While
                month += 1
            End While
            year += 1
        End While
        year -= 1 : month -= 1 : day -= 1
        'MsgBox(year & " year " & month & " month " & day & " day")

        Return year

    End Function
    Private Function strHL7Date2Date(hl7strdate As String) As String
        Dim ADate As String
        ADate = Mid(hl7strdate, 7, 2) & "/" & Mid(hl7strdate, 5, 2) & "/" & Int(Mid(hl7strdate, 1, 4)) + 543
        Return ADate
    End Function
    Private Function strHL7Date2MsDate(hl7strdate As String) As String
        Dim ADate As String
        'ADate = Mid(hl7strdate, 7, 2) & "/" & Mid(hl7strdate, 5, 2) & "/" & Int(Mid(hl7strdate, 1, 4)) + 543
        ADate = Mid(hl7strdate, 1, 4).ToString() & "-" & Mid(hl7strdate, 5, 2) & "-" & Mid(hl7strdate, 7, 2)
        Return ADate
    End Function
    Private Function strHL7DateTime2Time(hl7strdate As String) As String
        Dim ADate As String
        ADate = Mid(hl7strdate, 9, 2) & ":" & Mid(hl7strdate, 11, 2) & ":" & Mid(hl7strdate, 13, 2)
        Return ADate
    End Function

    Public Function MsDate(ByVal strdate As Date) As String
        Dim strtime As String
        Dim aDate As String
        strtime = "00:00:00"
        ''aDate = Convert.ToDateTime(strdate).Day.ToString("00") & "-" +
        ''                        Convert.ToDateTime(strdate).Month.ToString("00") & "-" +
        ''                        Convert.ToDateTime(strdate).Year.ToString("0000")
        'aDate = Convert.ToDateTime(strdate).Year.ToString("0000") & "-" +
        '        Convert.ToDateTime(strdate).Month.ToString("00") & "-" +
        '        Convert.ToDateTime(strdate).Day.ToString("00")

        aDate = strdate.Year.ToString() + strdate.ToString("-MM-dd")

        Return aDate

    End Function

    Public Function MsDateFull(ByVal strdate As Date) As String
        Dim aDate As String

        aDate = strdate.Year.ToString() + strdate.ToString("MMdd") + "000000"

        Return aDate

    End Function
    Public Function MsDateTimeFull(ByVal strdate As DateTime) As String
        Dim aDate As String

        aDate = strdate.Year.ToString() + strdate.ToString("MMdd") + Format(strdate, "hhmmss")

        Return aDate

    End Function
    Public Function iQDate(ByVal strdate As Date) As String
        Dim strtime As String
        Dim aDate As String
        strtime = "00:00:00"
        ''aDate = Convert.ToDateTime(strdate).Day.ToString("00") & "-" +
        ''                        Convert.ToDateTime(strdate).Month.ToString("00") & "-" +
        ''                        Convert.ToDateTime(strdate).Year.ToString("0000")
        'aDate = Convert.ToDateTime(strdate).Year.ToString("0000") & "-" +
        '        Convert.ToDateTime(strdate).Month.ToString("00") & "-" +
        '        Convert.ToDateTime(strdate).Day.ToString("00")

        'aDate = strdate.ToString("-dd-MM") + strdate.Year.ToString()
        aDate = strdate.Year.ToString() + strdate.ToString("-MM-dd")


        Return aDate

    End Function

    Public Function MsDateTime(ByVal strdate As Date, ByVal strtime As DateTime) As String

        Dim aDateTime As String

        aDateTime = strdate.Year.ToString() + strdate.ToString("-MM-dd") + " " & Format(strtime, "hh:mm:ss")

        Return aDateTime
    End Function

    Public Function iQTime(ByVal strdatetime As DateTime) As String

        Dim aDateTime As String

        aDateTime = Format(strdatetime, "hh:mm:ss")

        Return aDateTime
    End Function
    Public Function HL7DateTime() As String
        Dim resultDate As String
        Dim aDateTime As DateTime = Now

        resultDate = aDateTime.Year.ToString() + Format(aDateTime, "MMdd") + Format(aDateTime, "hhmmss")

        Return resultDate
    End Function
    Public Function HL7Date() As String
        Dim resultDate As String
        Dim aDateTime As DateTime = Now

        resultDate = aDateTime.Year.ToString() + Format(aDateTime, "MMdd")

        Return resultDate
    End Function


    'Public watchfolder As FileSystemWatcher

    Private Sub cmdStart_Click(sender As System.Object, e As System.EventArgs) Handles cmdStart.Click
        Me.txtTracker.Text = ver & " Running ... " & Format(Now, "dd/MM/yyyy hh:mm:ss")
        Me.txtConsole.Text = " Begin ... " & Format(Now, "dd/MM/yyyy hh:mm:ss") & vbNewLine & Me.txtConsole.Text
        Me.IntervalTimer.Interval = Val(Me.txtInterval.Text) * 1000
        Me.IntervalTimer.Enabled = True

        cmdStart.Enabled = False
        cmdStop.Enabled = True


        '-------------------------------------------
        'mFileName = InboxOutboxController.Instance.InboxFolder & "ORM-O01_CT_1121505246_NW.txt"
        'Me.txtConsole.Text = mFileName & vbNewLine & Me.txtConsole.Text

        '-------------------------------------------

    End Sub




    Private Sub cmdStop_Click(sender As System.Object, e As System.EventArgs) Handles cmdStop.Click
        Me.txtTracker.Text = "Sleeping....zzzz"
        Me.txtConsole.Text = " End ... " & Format(Now, "dd/MM/yyyy hh:mm:ss") & vbNewLine & Me.txtConsole.Text
        Me.IntervalTimer.Enabled = False

        'watchfolder.EnableRaisingEvents = False
        cmdStart.Enabled = True
        cmdStop.Enabled = False

    End Sub

    Private Sub IntervalTimer_Tick(sender As System.Object, e As System.EventArgs) Handles IntervalTimer.Tick

        Me.txtTracker.Text = ver & " Running ... " & Format(Now, "dd/MM/yyyy hh:mm:ss")
        '=====HL7 Order Data ===========
        GetImportData()
        '=====HL7 Check Image Data ===========
        GetImageData()
        '=====HL7 Check Report Data ===========
        GetReportData()

    End Sub

    ' This method shows how to move files from one folder to another folder.

    'Public Sub MoveFiles(ByVal sourcePath As String, ByVal DestinationPath As String)
    '    If (Directory.Exists(sourcePath)) Then
    '        For Each fName As String In Directory.GetFiles(sourcePath)
    '            If File.Exists(fName) Then
    '                Dim dFile As String = String.Empty
    '                dFile = Path.GetFileName(fName)
    '                Dim dFilePath As String = String.Empty
    '                dFilePath = DestinationPath + dFile
    '                File.Move(fName, dFilePath)
    '            End If
    '        Next
    '    End If
    'End Sub

    Public Sub MoveFiles(ByVal sourcePath As String, ByVal DestinationPath As String, ByVal sfName As String)
        If (Directory.Exists(sourcePath)) Then
            'For Each fName As String In Directory.GetFiles(sourcePath)
            Dim fName As String = sourcePath & sfName
            If File.Exists(fName) Then
                Dim dFile As String = String.Empty
                dFile = Path.GetFileName(fName)
                Dim dFilePath As String = String.Empty
                If (Directory.Exists(DestinationPath)) Then

                    dFilePath = DestinationPath + dFile
                Else

                    Directory.CreateDirectory(DestinationPath)
                    dFilePath = DestinationPath + dFile

                End If


                File.Move(fName, dFilePath)

            End If
            'Next
        End If
    End Sub

    Public Sub MoveDupliCateFiles(ByVal sourcePath As String, ByVal DestinationPath As String, ByVal sfName As String)
        If (Directory.Exists(sourcePath)) Then
            'For Each fName As String In Directory.GetFiles(sourcePath)
            Dim fName As String = sourcePath & sfName
            If File.Exists(fName) Then
                Dim dFile As String = String.Empty
                dFile = Path.GetFileName(fName)
                Dim dFilePath As String = String.Empty
                If (Directory.Exists(DestinationPath)) Then

                    dFilePath = DestinationPath + dFile
                Else

                    Directory.CreateDirectory(DestinationPath)
                    dFilePath = DestinationPath + dFile

                End If
                Dim SdFilePath = dFilePath & Format(Now, "yyyyMMddhhmmss") & ".txt"

                'File.Move(fName, dFilePath)
                'My.Computer.FileSystem.MoveFile(fName, SdFilePath,
                '    FileIO.UIOption.AllDialogs,
                '    FileIO.UICancelOption.ThrowException)

                My.Computer.FileSystem.CopyFile(fName, SdFilePath,
                    Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
                    Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

                DeleteDataFile(sourcePath, sfName)

            End If
            'Next
        End If
    End Sub

    ' This method shows how to copy files from one folder to another folder.

    Public Sub CopyFiles(ByVal sourcePath As String, ByVal DestinationPath As String)
        If (Directory.Exists(sourcePath)) Then
            For Each fName As String In Directory.GetFiles(sourcePath)
                If File.Exists(fName) Then
                    Dim dFile As String = String.Empty
                    dFile = Path.GetFileName(fName)
                    Dim dFilePath As String = String.Empty
                    dFilePath = DestinationPath + dFile
                    File.Copy(fName, dFilePath, True)
                End If
            Next
        End If
    End Sub
    Public Sub DeleteDataFile(ByVal sourcePath As String, ByVal sfName As String)
        'My.Computer.FileSystem.DeleteFile(FileDirPath,
        '    Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
        '    Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin)

        'My.Computer.FileSystem.DeleteFile(FileDirPath,
        'Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
        'Microsoft.VisualBasic.FileIO.RecycleOption.DeletePermanently,
        'Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

        If (Directory.Exists(sourcePath)) Then
            'For Each fName As String In Directory.GetFiles(sourcePath)
            Dim fName As String = sourcePath & sfName
            If File.Exists(fName) Then
                File.Delete(fName)
            End If
        End If


    End Sub

    ' Delete file 
    Public Sub DeleteFilesFromFolders(ByVal DirPath As String)
        If (Directory.Exists(DirPath)) Then
            For Each fName As String In Directory.GetFiles(DirPath)
                If File.Exists(fName) Then
                    File.Delete(fName)
                End If
            Next
        End If

        
    End Sub

    Private Function ModalityGroup(ByVal strGroup As String) As String
        Dim Modal As String
        Select Case Trim(strGroup)

            Case "1"
                Modal = "CR"
                ' X-Ray
            Case "2"
                Modal = "US"
                'Ultrasound
            Case "3"
                Modal = "CT"
                ' CT
            Case "4"
                Modal = "MRI"
                'MRI
            Case "5"
                Modal = "MAM"
                'Mammogram

        End Select
        Return Modal

    End Function

    Private Function TH2R(ByVal s As String) As String
        Dim tp As String = Trim(Thai2RomanPath)
        My.Computer.FileSystem.WriteAllText(tp & "\data.txt", Trim(s), False, System.Text.ASCIIEncoding.Default)
        tt.Initial(tp)
        tt.RomanUnicodeFile(tp & "\data.txt")
        TH2R = Trim(My.Computer.FileSystem.ReadAllText(tp & "\data.txt.rom"))
        TH2R = Replace(TH2R, " ", "")
        TH2R = Microsoft.VisualBasic.Left(TH2R, Len(TH2R) - 2)
    End Function

    Public Function HL7ReserverClear(ByVal str As String) As String
        str = Replace(str, "|", "")
        str = Replace(str, "~", "")
        str = Replace(str, "\", "")
        str = Replace(str, "/", "")
        str = Replace(str, "&", "")
        str = Replace(str, "'", "")
        str = Replace(str, """", "")
        str = Replace(str, "(", "")
        str = Replace(str, ")", "")
        str = Replace(str, "-", "")
        str = Replace(str, ",", " ")
        str = Replace(str, " ", "^")
        str = Replace(str, "1", "")
        str = Replace(str, "2", "")
        str = Replace(str, "3", "")
        str = Replace(str, "4", "")
        str = Replace(str, "5", "")
        str = Replace(str, "6", "")
        str = Replace(str, "7", "")
        str = Replace(str, "8", "")
        str = Replace(str, "9", "")
        str = Replace(str, "0", "")

        HL7ReserverClear = str
    End Function

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        ''Export2HL7ImageData(111880813)
        Export2HL7ReportData(111880817)

    End Sub
End Class